//index.js
let app = getApp();
let login = require('../../utils/login');
let $api = require('../../config');
Page({
    onLoad(option){
        let shareId = option.shareId
        if(shareId){
          wx.setStorageSync('shareId',shareId);
        }
    },
    data: {
        /*剩余查询次数*/
        surplusSearch:0,
        /*多少人查询*/
        queryTotal:1000,
        /*stockList*/
        stockList:[],
        stockListBase:[],
        sortEq:{
            dqj:0
        },
        /*热搜*/
        hostList:[],
        /*会员价格*/
        price:[],
        /**弹窗 */
        pricePup:true,
        /**证券指数*/
        stokeIndex:[],
        /**指数pe */
        stokePe:[],
        // 是否为会员
        isVip:true
    },
    /*分享*/
    onShareAppMessage: function (res) {
        let id = wx.getStorageSync('userInfo').user_id;
        if (res.from === 'button') {
            return {
                title: '股票估值查询',
                path: `/pages/index/index?shareId=${id}`,
                imageUrl:'../../images/share-img.png'
            }
        }else{
            return {
                title: '股票估值查询',
                path: `/pages/index/index?shareId=${id}`,
                imageUrl:'../../images/share-img.png'
            }
        }
    },
    /*初次渲染*/
    onReady(){
        this.checkLogin();
        wx.request({
            url:'https://gupiao.test.saiguhui.com/index/user2/dopay?type=3',
            method:'GET',
            success:function (res) {
                console.log(res);
            }
        })
    },
    onShow(){
        let self = this;
        wx.getSetting({
            success: function(res){
                let token = wx.getStorageSync('userInfo').token;
                /*用户授权*/
                if (res.authSetting['scope.userInfo'] && token) {
                    self.getStockList();
                    self.getSurplusSearch();
                    // self.getHot();//热搜
                    self.getShare();
                    self.getStockOnLine();
                    // self.getStockPe();
                }else{
                    
                }
            }
        });
        this.toSeach();
    },
    /*
    获取自选股列表
    */
    getStockList(){
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        wx.request({
            url:$api.api.stockList,
            method:'GET',
            data: {
                token
            },
            header: {
                'content-type': 'application/json' 
            },
            success: function(res) {
                let stockList = res.data.data;
                // stockList = [
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3%'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'},
                //     {idx:1,name:'平安银行',code:'000001',dqj:'2222',gz:'3333'}
                //     ];
                self.setData({
                  stockList:stockList,
                  stockListBase:stockList
                })
            }
        })
    },

    /*获取热搜*/
    getHot(){
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        wx.request({
            url:$api.api.hot, 
            method:'GET',
            data: {
                token
            },
            header: {
                'content-type': 'application/json' 
            },
            success: function(res) {
                let data = res.data.data;
                // let hostList = data.hot;
                let queryTotal = data.total_query_times;
                let price = data.price;
                self.setData({
                    queryTotal:queryTotal,
                    // hostList:hostList,
                    price:price
                })
            }
        })
    },
    /*查看是否授权*/
    checkLogin(){
        let self = this;
        wx.getSetting({
            success: function(res){
                /*用户授权*/
                if (res.authSetting['scope.userInfo']) {
                    login.Login((res)=>{
                        let data = JSON.parse(res.message);
                        self.setData({
                            useInfo:data.data
                        })
                        wx.setStorageSync('userInfo',data.data);
                        self.getStockList();
                        self.getSurplusSearch();
                        self.getHot();//热搜
                    })
                }else{
                 /*用户没有授权*/
                 wx.showModal({
                    title: '提示',
                    content: '此小程序必须用户授权,不然获取不到数据',
                    success: function(res) {
                        if (res.confirm) {
                            wx.redirectTo({
                                url: '../user/user'
                            })
                        } else if (res.cancel) {
                        }
                    }
                  })
                }
            }
        })
    },
    /*分享*/
    getShare(){
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        let shareId = wx.getStorageSync('shareId');
        if(shareId){
            wx.request({
                url:$api.api.from, 
                method:'GET',
                data: {
                    token,
                    id:shareId
                },
                header: {
                    'content-type': 'application/json' 
                },
                success: function(res) {
                    let data = res.data;
                    if(data.errCode == 0 || data.msg == '成功'){
                        self.getSurplusSearch();
                        wx.removeStorageSync('shareId')
                    }
                }
            })
        }
    },
    toSeach(){
        let self = this;
        this.getSurplusSearch((surplusTotal)=>{
          if(surplusTotal == 0){
            wx.showModal({
                title: '提示',
                content: '您的查询次数已经用完,是否需要购买会员?',
                success: function(res) {
                    if (res.confirm) {
                        wx.switchTab({
                            url:'../pay/pay'
                        })
                    } else if (res.cancel) {
                        self.setData({
                            isVip:false  //不是会员
                        })
                    }
                }
            })
          }else{
                // wx.navigateTo({
                //   url:'../search/search'
                // })
            }
        })
    },
    toDetails(e){
        let code = e.currentTarget.dataset.code;
        let isOwn = e.currentTarget.dataset.isown;
        wx.navigateTo({
            // url:`../klineDetail/klineDetail?code=${code}&isOwn=${isOwn}`
            url:`../klineDetail/klineDetail?code=${code}&from=index`
        })
    },
    // toklineDetails(e){
    //     let code = e.currentTarget.dataset.code;
    //     wx.navigateTo({
    //         url:`../klineDetail/klineDetail?code=${code}&from=index`
    //     })
    // },
    del(){
        let code = e.currentTarget.dataset.code
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        wx.showModal({
            title: '提示',
            content: '是否确定删除此条自选股',
            success: function(res) {
                if (res.confirm) {
                    wx.request({
                        url:$api.api.stockDel, 
                        method:'GET',
                        data: {
                            token,
                            code
                        },
                        header: {
                                'content-type': 'application/json' 
                        },
                        success: function(res) {
                            let data = res.data;
                            if(data.errCode == 0 || data.msg == '成功'){
                                wx.showToast({
                                    title: '删除成功',
                                    icon: 'success',
                                    duration: 2000
                                })
                                self.getStockList();
                            }
                      
                        }
                    })
                } else if (res.cancel) {
                }
            }
		})
    },
    toPay(){
        wx.navigateTo({
          url:'../pay/pay'
        })
    },
    toStock(){
        wx.navigateTo({
            url:'../stockLine/stockLine'
        })
    },
 // 搜索
    search(e){
        var val = e.detail.value;
        this.getResult(val);
    },
    /*获取结果*/
    getResult(val){
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        self.setData({
            showResult:true
        })
        wx.showLoading({
            title: '搜索中',
        })
        wx.request({
            url:$api.api.search,
            method:'GET',
            data: {
                token,
                key:val
            },
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                let data = res.data;
                let searchList = data.data;
                self.setData({
                    searchList
                })
                wx.hideLoading();
            }
        })
    },
    // 取消搜索
    cancelSearch:function(){
        var self = this;
        self.setData({
            showResult:false
        })
    },
    /*
   * 查询次数
   */
    getSurplusSearch(cb){
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        wx.request({
            url:$api.api.surplusSearch,
            method:'GET',
            data: {
                token
            },
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                let surplusTotal = res.data.data.left_query_times;
                self.setData({
                    surplusSearch:surplusTotal
                })
                cb && cb(surplusTotal)
            }
        })
    },
    // 证券指数
    getStockOnLine(){
        let token = wx.getStorageSync('userInfo').token;
        let self = this;
        wx.request({
            url:$api.api.stockOnLine,
            method:'GET',
            data: {
                token
            },
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                let stokeIndex = res.data.data;
                self.setData({
                    stokeIndex
                })
            }
        })
    },
    // 股票列表--序号排序
    listSortFuc:function () {
        var self = this;
        var listData = self.data.stockListBase;
        if (listData.length>1){
            listData = listData.reverse();
            self.setData({
                stockList:listData
            })
        }
    },
    // // pe
    // getStockPe(){
    //     let token = wx.getStorageSync('userInfo').token;
    //     let self = this;
    //     wx.request({
    //         url:$api.api.stockPe,
    //         method:'GET',
    //         data: {
    //             token
    //         },
    //         header: {
    //             'content-type': 'application/json'
    //         },
    //         success: function(res) {
    //             let stockList = res.data.data;
    //             self.setData({
    //                 stockList
    //             })
    //         }
    //     })
    // },
    // 普通字段排序
    normalSortFuc:function (e) {
        var self = this;
        var eq = e.currentTarget.dataset.eq;
        var btnName = e.currentTarget.dataset.btnname;
        var listData = self.data.stockListBase;
        //  var listData = [1,2,3,4,5,6,'-',6,9,'-'];
        var thisData = [];//取出当前字段列表
        var emptyData = [];//空值数据单独组装
        var zsData = [];//正数数据排序组装
        var zsDataIndex = [];//正数数据排序组索引装
        var fsDataIndex = [];//负数数据排序索引组装
        var Index = [];//数据排序索引组装
        var newStockList = [];
        // console.log(listData[0][btnName]);
        for (var i=0;i<listData.length;i++) {
            if (listData[i][btnName] !== '-'&&listData[i][btnName] !== '') {
                if (listData[i][btnName]>0||listData[i][btnName]==0){
                    zsDataIndex.push(listData[i][btnName])
                }else{
                    fsDataIndex.push(listData[i][btnName])
                }
            }else{
                emptyData.push(listData[i])
            }
        }
        if (btnName=='pe'){
            Index = fsDataIndex.sort(self.test).reverse().concat(zsDataIndex.sort(self.test).reverse());
        } else{
            Index = fsDataIndex.sort(self.test).concat(zsDataIndex.sort(self.test));
        }



        for (var i=0;i<Index.length;i++){
            for (var j=0;j<listData.length;j++){
                if (Index[i]==listData[j][btnName]){
                    zsData.push(listData[j]);
                }
            }
        }

        // console.log(zsData);
        // console.log(zsData);

        if (eq==0) {
            newStockList = zsData.concat(emptyData);
            self.setData({
                ['sortEq.'+btnName]:1,
                stockList:newStockList
            })
        }else{
            newStockList = zsData.reverse().concat(emptyData);
            self.setData({
                ['sortEq.'+btnName]:0,
                stockList:newStockList
            })
        }

    },
    // pe字段排序
    peSortFuc:function () {

    },
    goDistinct:function () {
        wx.redirectTo({
            url:'..distinct/distinct'
        })
    }
});
